package com.module.circle.widget

import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.util.AttributeSet
import android.util.TypedValue
import android.view.Gravity
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.common.base.app.extras.loadCircle
import com.module.circle.R
import kotlin.math.min

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/07/24
 *
 * 描述：多头像显示控件 - ImageView方案  根据传入的String数组动态添加ImageView显示头像
 *
 * 修订历史：
 *
 */
class MultiAvatarView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    // 默认值
    private var avatarSize = 40.dpToPx()
    private var overlapWidth = 12.dpToPx()
    private var borderWidth = 2.dpToPx()
    private var borderColor = Color.WHITE
    private var maxCount = 5
    private var showMoreText = "+%d"
    private var moreTextSize = 12.spToPx()
    private var moreTextColor = Color.GRAY
    private var moreBackground = Color.parseColor("#F0F0F0")
    private var defaultAvatarRes = R.mipmap.ic_logo_launcher_round

    // 头像数据
    private var avatarUrls: List<String> = emptyList()
    private val avatarViews = mutableListOf<ImageView>()
    private var moreTextView: TextView? = null
    private var showMoreIndicator = false  // 是否显示更多指示器

    init {
        initAttrs(attrs)
    }

    private fun initAttrs(attrs: AttributeSet?) {
        attrs?.let {
            val typedArray = context.obtainStyledAttributes(it, R.styleable.MultiAvatarView)

            avatarSize = typedArray.getDimensionPixelSize(
                R.styleable.MultiAvatarView_mav_avatarSize,
                avatarSize
            )
            overlapWidth = typedArray.getDimensionPixelSize(
                R.styleable.MultiAvatarView_mav_overlapWidth,
                overlapWidth
            )
            borderWidth = typedArray.getDimensionPixelSize(
                R.styleable.MultiAvatarView_mav_borderWidth,
                borderWidth
            )
            borderColor = typedArray.getColor(
                R.styleable.MultiAvatarView_mav_borderColor,
                borderColor
            )
            maxCount = typedArray.getInt(
                R.styleable.MultiAvatarView_mav_maxCount,
                maxCount
            )
            showMoreText = typedArray.getString(
                R.styleable.MultiAvatarView_mav_showMoreText
            ) ?: showMoreText
            moreTextSize = typedArray.getDimensionPixelSize(
                R.styleable.MultiAvatarView_mav_moreTextSize,
                moreTextSize
            )
            moreTextColor = typedArray.getColor(
                R.styleable.MultiAvatarView_mav_moreTextColor,
                moreTextColor
            )
            moreBackground = typedArray.getColor(
                R.styleable.MultiAvatarView_mav_moreBackground,
                moreBackground
            )
            defaultAvatarRes = typedArray.getResourceId(
                R.styleable.MultiAvatarView_mav_defaultAvatar,
                defaultAvatarRes
            )
            showMoreIndicator = typedArray.getBoolean(
                R.styleable.MultiAvatarView_mav_showMoreIndicator,
                showMoreIndicator
            )
            typedArray.recycle()
        }
    }

    /**
     * 设置头像URL列表
     */
    fun setAvatarUrls(urls: List<String>) {
        avatarUrls = urls
        setupAvatars()
    }

    private fun setupAvatars() {
        // 清除现有视图
        removeAllViews()
        avatarViews.clear()
        moreTextView = null

        if (avatarUrls.isEmpty()) return

        // maxCount 只控制头像ImageView的创建数量
        val avatarDisplayCount = min(avatarUrls.size, maxCount)

        // 创建头像ImageView
        for (i in 0 until avatarDisplayCount) {
            createAvatarView(i, avatarUrls[i])
        }

        // 独立控制更多指示器的显示
        if (showMoreIndicator && avatarUrls.size > maxCount) {
            // 在最后位置创建更多指示器
            createMoreIndicator(avatarDisplayCount)
        }

        // 更新布局
        requestLayout()
    }

    private fun createAvatarView(index: Int, url: String) {
        val imageView = ImageView(context).apply {

            // 设置布局参数
            layoutParams = LayoutParams(avatarSize, avatarSize).apply {
                leftMargin = index * (avatarSize - overlapWidth)
                gravity = Gravity.CENTER_VERTICAL
            }
//            // 设置边框
//            borderWidth = this@MultiAvatarView.borderWidth
//            borderColor = this@MultiAvatarView.borderColor
            // 设置层级，确保右边的头像在上层（下一个叠在上一个上面）
            elevation = index.toFloat()
        }

//        placeholder = R.mipmap.ic_logo_launcher_round
        imageView.loadCircle(url, placeholder = R.mipmap.ic_logo_avatar, borderSize = borderWidth,borderColor = borderColor)

        avatarViews.add(imageView)
        addView(imageView)
    }

    private fun createMoreIndicator(index: Int) {
        // 创建圆形背景的TextView
        val textView = TextView(context).apply {
            // 设置文本 - 显示超出maxCount的数量
            val moreCount = avatarUrls.size - maxCount
            text = String.format(showMoreText, moreCount)

            // 设置样式
            setTextColor(moreTextColor)
            setTextSize(TypedValue.COMPLEX_UNIT_PX, moreTextSize.toFloat())
            gravity = Gravity.CENTER
            typeface = Typeface.DEFAULT_BOLD

            // 设置背景
            background = ContextCompat.getDrawable(context, R.drawable.common_head_white_circle_bg)?.apply {
                setTint(moreBackground)
            }

            // 设置布局参数
            layoutParams = LayoutParams(avatarSize, avatarSize).apply {
                leftMargin = index * (avatarSize - overlapWidth)
                gravity = Gravity.CENTER_VERTICAL
            }

            // 设置层级，确保"+N"指示器在最上层
            elevation = index.toFloat()
        }

        moreTextView = textView
        addView(textView)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val avatarDisplayCount = min(avatarUrls.size, maxCount)
        // 计算总宽度时需要考虑更多指示器
        val totalDisplayCount = if (showMoreIndicator && avatarUrls.size > maxCount) {
            avatarDisplayCount + 1
        } else {
            avatarDisplayCount
        }

        val totalWidth = if (totalDisplayCount <= 1) {
            avatarSize
        } else {
            avatarSize + (totalDisplayCount - 1) * (avatarSize - overlapWidth)
        }

        val width = totalWidth + paddingLeft + paddingRight
        val height = avatarSize + paddingTop + paddingBottom

        setMeasuredDimension(
            resolveSize(width, widthMeasureSpec),
            resolveSize(height, heightMeasureSpec)
        )

        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }

    /**
     * 获取头像数量
     */
    fun getAvatarCount(): Int = avatarUrls.size

    /**
     * 设置头像点击监听
     */
    fun setOnAvatarClickListener(listener: (index: Int, url: String) -> Unit) {
        avatarViews.forEachIndexed { index, imageView ->
            imageView.setOnClickListener {
                if (index < avatarUrls.size) {
                    listener(index, avatarUrls[index])
                }
            }
        }

        moreTextView?.setOnClickListener {
            // 点击更多按钮的处理
            listener(-1, "") // -1 表示点击的是更多按钮
        }
    }

    /**
     * 更新特定位置的头像
     */
    fun updateAvatar(index: Int, url: String) {
        if (index < 0 || index >= avatarUrls.size) return

        val mutableList = avatarUrls.toMutableList()
        mutableList[index] = url
        avatarUrls = mutableList

        // 重新加载对应的ImageView
        if (index < avatarViews.size) {
            val imageView = avatarViews[index]
//            if (url.isBlank()) {
//                imageView.setImageResource(defaultAvatarRes)
//            } else {
//                Glide.with(context)
//                    .load(url)
//                    .placeholder(defaultAvatarRes)
//                    .error(defaultAvatarRes)
//                    .transform(CircleCrop())
//                    .into(imageView)
//            }

            imageView.loadCircle(url, placeholder = R.mipmap.ic_logo_avatar, borderSize = borderWidth, borderColor = borderColor)
        }
    }

    // 扩展函数
    private fun Int.dpToPx(): Int {
        return (this * context.resources.displayMetrics.density).toInt()
    }

    private fun Int.spToPx(): Int {
        return (this * context.resources.displayMetrics.scaledDensity).toInt()
    }
}